<template>
  <div class="articles-manage">
    <div class="page-header">
      <h2>养生文章管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加文章
      </el-button>
    </div>

    <!-- 文章列表 -->
    <el-table :data="articles" style="width: 100%" v-loading="loading">
      <el-table-column prop="title" label="标题" min-width="200" />
      <el-table-column prop="category" label="分类" width="120" />
      <el-table-column prop="author" label="作者" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="标签" width="200">
        <template #default="{ row }">
          <el-tag v-for="tag in row.tags" :key="tag" size="small" class="mx-1">
            {{ tag }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="60%"
      :before-close="handleDialogClose"
      :append-to-body="true"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select
            v-model="form.category"
            placeholder="请选择或输入文章分类"
            allow-create
            filterable
          >
            <el-option
              v-for="cat in categories"
              :key="cat"
              :label="cat"
              :value="cat"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入标签"
          >
            <el-option
              v-for="tag in commonTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="10"
            placeholder="请输入文章内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'ArticlesManage',
  components: {
    Plus
  },
  setup() {
    const articles = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const formRef = ref(null)
    const isEdit = ref(false)
    const currentId = ref(null)

    // 预设分类
    const presetCategories = [
      '养生知识',
      '健康指南',
      '用药指导'
    ]
    // 动态分类集合
    const categories = ref([...presetCategories])

    const commonTags = [
      '冬季养生',
      '健康生活',
      '感冒预防',
      '免疫力',
      '合理用药',
      '用药安全'
    ]

    const form = ref({
      title: '',
      category: '',
      author: '',
      content: '',
      tags: []
    })

    const rules = {
      title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
      category: [{ required: true, message: '请选择文章分类', trigger: 'change' }],
      author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
      content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
      tags: [{ required: true, message: '请选择或输入标签', trigger: 'change' }]
    }

    // 获取文章列表
    const fetchArticles = async () => {
      loading.value = true
      try {
        const response = await axios.get('http://localhost:3000/healthArticles')
        // 确保数据是数组格式，并且每个项目都有必要的字段
        const validArticles = Array.isArray(response.data) ? response.data : []
        articles.value = validArticles.map(article => ({
          id: article.id || '',
          title: article.title || '',
          content: article.content || '',
          category: article.category || '',
          author: article.author || '',
          createTime: article.createTime || new Date().toISOString().split('T')[0],
          tags: Array.isArray(article.tags) ? article.tags : []
        }))
        // 更新分类集合
        updateCategories()
      } catch (error) {
        console.error('获取文章列表失败:', error)
        ElMessage.error('获取文章列表失败')
        articles.value = []
      } finally {
        loading.value = false
      }
    }

    // 更新分类集合
    const updateCategories = () => {
      const allCategories = [
        ...presetCategories,
        ...articles.value.map(a => a.category).filter(Boolean)
      ]
      categories.value = Array.from(new Set(allCategories))
    }

    // 添加文章
    const handleAdd = () => {
      isEdit.value = false
      dialogTitle.value = '添加文章'
      form.value = {
        title: '',
        category: '',
        author: '',
        content: '',
        tags: []
      }
      dialogVisible.value = true
    }

    // 编辑文章
    const handleEdit = (row) => {
      isEdit.value = true
      currentId.value = row.id
      dialogTitle.value = '编辑文章'
      form.value = { ...row }
      dialogVisible.value = true
    }

    // 删除文章
    const handleDelete = (row) => {
      ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await axios.delete(`http://localhost:3000/healthArticles/${row.id}`)
          ElMessage.success('删除成功')
          fetchArticles()
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const articleData = {
              ...form.value,
              createTime: new Date().toISOString().split('T')[0]
            }
            
            if (isEdit.value) {
              await axios.put(`http://localhost:3000/healthArticles/${currentId.value}`, articleData)
              ElMessage.success('更新成功')
            } else {
              await axios.post('http://localhost:3000/healthArticles', articleData)
              ElMessage.success('添加成功')
            }
            dialogVisible.value = false
            await fetchArticles() // 重新获取列表并更新分类
            updateCategories()
          } catch (error) {
            console.error('操作失败:', error)
            ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
          }
        }
      })
    }

    // 关闭对话框
    const handleDialogClose = (done) => {
      ElMessageBox.confirm('确认关闭？未保存的内容将会丢失')
        .then(() => {
          done()
        })
        .catch(() => {})
    }

    onMounted(() => {
      fetchArticles()
    })

    return {
      articles,
      loading,
      dialogVisible,
      dialogTitle,
      form,
      formRef,
      rules,
      commonTags,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSubmit,
      handleDialogClose,
      categories
    }
  }
}
</script>

<style scoped>
.articles-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  color: black;
}

.el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 